package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.config.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.AlipayService;
import com.spzx.payment.service.PaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.service.GenericResponseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.spzx.common.core.web.domain.AjaxResult.success;

/**
 * ClassName: AlipayController
 * Description:
 *
 * @Author linz
 * @Creat 2025/3/25 18:28
 * @Version 1.00
 */
@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private RabbitService rabbitService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("/submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo){
        String form = alipayService.submitAlipay(orderNo);
        System.out.println("form............... : " + form);
        return success(form);
    }

    @RequestMapping("/callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap) {
        log.info("AlipayController...alipayNotify方法执行了...");

        String result = "failure";
        try {
            //调用SDK验证签名
            //1.去掉sign和sign_type 参数将剩下的参数进行字典排序成字符串，得到待签名字符串
            //2.将签名参数(sign)使用base64 解码为字节码传
            //3.使用支付宝公钥和RSA2算法进行签名验证，如果验证成功，则说明该通知是支付宝发出的，并且是经过支付宝验签成功的。
            boolean signVerified = false;
            signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type
            );
            //校验验签是否成功
            String outTradeNo = paramMap.get("out_trade_no");
            if(!signVerified){
                log.error("订单 {} 验签失败", outTradeNo);
                return result;
            }
            log.error("订单 {} 验签成功", outTradeNo);
            // 交易状态
            String tradeStatus = paramMap.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {

                // 幂等性判断
                PaymentInfo paymentInfo = paymentInfoService.getOne(
                        new LambdaQueryWrapper<PaymentInfo>()
                                .eq(PaymentInfo::getOrderNo, outTradeNo)
                                .eq(PaymentInfo::getPayType, 2)
                );
                if(paymentInfo.getPaymentStatus() == 1){
                    return "success";
                }

                // 更新交易记录状态
                paymentInfoService.updatePaymentStatus(paymentInfo, paramMap);

                //修改订单状态
                rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, outTradeNo);
                //扣减库存
                rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_MINUS, outTradeNo);

            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return "success" ;
    }
}
